//
//  NewRepairViewController.m
//  PlantGoWorker
//
//  Created by 纪翀 on 2017/9/25.
//  Copyright © 2017年 m-training. All rights reserved.
//

#import "NewRepairViewController.h"
#import "ImageCollectionViewCell.h"
#import "MJPhotoBrowser.h"
#import "MJPhoto.h"
#import "GTMBase64.h"

@interface NewRepairViewController ()
{
    NSMutableArray *_picArr;
    UIImagePickerController *_picker;
    NSDictionary *_photoInfo;
}
@end

@implementation NewRepairViewController

-(void)initCollectionView{
    [_collectionView registerNib:[UINib nibWithNibName:@"ImageCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
    UICollectionViewFlowLayout *flowLayout = [_collectionView collectionViewLayout];
    [flowLayout setMinimumLineSpacing:0];
    [flowLayout setMinimumInteritemSpacing:0];
}

- (void)initImagePicker{
    _picker = [[UIImagePickerController alloc] init];
    
    // 设置代理
    _picker.delegate = self;
    
    // 设置是否需要做图片编辑，default NO
    _picker.allowsEditing = YES;
}

- (void)loadData{
    NSString *resId = [_resDic objectForKey:@"id"];
    NSString *resConfName = [_resDic objectForKey:@"resConfName"];
    NSString *stockroomName = [_resDic objectForKey:@"stockroomName"];
    NSString *storageAddress = [_resDic objectForKey:@"storageAddress"];
    [_barCodeLabel setText:[@"编码: " stringByAppendingString:resId]];
    [_resConfLabel setText:[@"品种: " stringByAppendingString:resConfName]];
    [_stockLabel   setText:[@"品种: " stringByAppendingString:stockroomName]];
    [_storageLabel setText:[@"仓库: " stringByAppendingString:storageAddress]];
    [_descTextView setText:@""];
    [_descTextView.layer setBorderColor:[UIColor blackColor].CGColor];
    _descTextView.layer.borderWidth = 1.0f;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadData];
    [self initCollectionView];
    [self initImagePicker];
    
    _picArr = [NSMutableArray arrayWithCapacity:3];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (void)removePic:(UIButton *)btn
{
    NSLog(@"upInside...");
    [_picArr removeObjectAtIndex:btn.tag];
    [_collectionView reloadData];
}

#pragma mark --- <UICollectionView>

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    CGSize size={0,0};
    return size;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return [_picArr count]+1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    ImageCollectionViewCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    if ([_picArr count] == indexPath.row){
        [cell.imgView setImage:[UIImage imageNamed:@"camera.png"]];
        [cell.delBtn setHidden:YES];

    }else{
        NSDictionary *photoInfo = [_picArr objectAtIndex:indexPath.row];
        [cell.imgView setImage:[photoInfo objectForKey:UIImagePickerControllerOriginalImage]];
        [cell.delBtn setHidden:NO];
        if ([cell.delBtn.allTargets count] > 0){
            [cell.delBtn removeTarget:self action:@selector(removePic:) forControlEvents:UIControlEventTouchUpInside];
        }

        cell.delBtn.tag = indexPath.row;
        [cell.delBtn addTarget:self action:@selector(removePic:) forControlEvents:UIControlEventTouchUpInside];
        
    }

    return cell;
}



- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row > 2){
//        超过三张照片就无法再加
        return;
    }
    
    if (indexPath.row == [_picArr count]){
        // 打开相机 准备拍照
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            //        _picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            _picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:_picker animated:YES completion:nil];
        }
    }
    else{
        NSMutableArray * photos = [[NSMutableArray alloc] init];
        for (int i = 0; i < [_picArr count]; i ++ )
        {
            MJPhoto * photo = [[MJPhoto alloc] init];
            NSDictionary *_photoInfo = [_picArr objectAtIndex:i];
            NSData * data = UIImageJPEGRepresentation([_photoInfo objectForKey:UIImagePickerControllerOriginalImage], 1);
            
            photo.image = [UIImage imageWithData:data];
            [photos addObject:photo];
        }
        //显示
        MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
        browser.photos          = photos;
        browser.currentPhotoIndex = indexPath.row;
        
        [browser show];
    }
}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    return nil;
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    float cellw =[UIScreen mainScreen].bounds.size.width/3;
    return CGSizeMake(cellw, cellw);
}

//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    
    return UIEdgeInsetsMake(0, 0, 0, 0);
}


#pragma mark - ImagePicker
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    // 退出当前界面
    [picker dismissViewControllerAnimated:YES completion:nil];
}

// 选择完成
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    _photoInfo = info;
    NSString  *imageStr = [GTMBase64 stringByEncodingData:UIImageJPEGRepresentation([_photoInfo objectForKey:UIImagePickerControllerOriginalImage], 0.1)];
    
    [_picArr addObject:info];
    [_collectionView reloadData];
    [picker dismissViewControllerAnimated:YES completion:nil];
    

    
    
}

- (IBAction)submitBtnClick:(id)sender {
    NSString *token = [GlobalVar getVarName:@"token"];
    NSMutableArray *picArray = [NSMutableArray arrayWithCapacity:10];
    for (NSDictionary *photoInfo in _picArr){
        NSString  *imageStr = [GTMBase64 stringByEncodingData:UIImageJPEGRepresentation([photoInfo objectForKey:UIImagePickerControllerOriginalImage], 0.1)];
        [picArray addObject:imageStr];
    }
    NSDictionary *postDic = @{
                              @"type":[@"0" isEqualToString:_type] ? @0 : @1,//0为复壮1为报损
                              @"resId": [_resDic objectForKey:@"id"],//扫码的资源id
                              @"desc": _descTextView.text,
                              @"picCode": picArray,//多图上传 界面上限定三张
                              @"token":token
                              };
    [SendRequestClass commonRequest:@"/api/commitrepair" postDic:postDic completionBlock:^(NSDictionary *succDic) {
        if ([[succDic objectForKey:@"code"] intValue] == SUCC_RESP)
        {
            [self.navigationController popViewControllerAnimated:YES];
        }
        else{
            NSLog(@"Fail MyOffTimeList");
            [MyHint showHint:[succDic objectForKey:@"message"]];
        }
        
    } failureBlock:^(NSDictionary *failDic) {
        NSLog(@"Network error");
        [MyHint showHint:@"网络出现故障"];
    }];
}

@end
